package org.sapmentors.returns.service;

import java.util.ArrayList;
import java.util.Hashtable;

import java.io.*;
import java.net.*;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.sapmentors.WebserviceHelper;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import sun.security.jca.ServiceId;

public class CreateServiceRequest extends DefaultHandler {
 
	final String queryIgnore=".soap-env:Envelope.soap-env:Body.n0:ServiceRequestERPByIDResponse_sync.ServiceRequest.";
	final String createIgnore = ".soap-env:Envelope.soap-env:Body.n0:ServiceRequestERPCreateConfirmation_sync.";
  String serviceRequest ;
  Hashtable<String, String> statusResult = new Hashtable<String, String>();
	public CreateServiceRequest() {
	
	}
	
	public String getServiceRequest(String materialId, String description){
		 try {
			 // query to find service request number
			 HttpURLConnection connection=  WebserviceHelper.getConnection("http://erp.esworkplace.sap.com/sap/bc/srt/xip/sap/ECC_SRVCREQCRTRC?sap-client=800", getMessageCreateMessage(materialId, description));
	            
	            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	            	SAXParserFactory factory = SAXParserFactory.newInstance();
	                SAXParser saxParser = factory.newSAXParser();
	                
	                saxParser.parse(connection.getInputStream(), this);
	            } else {
	            	return "Could not create service request";
	            }
	            
	            getStatus(serviceRequest);
	               
	            
	            
	        } catch (Exception e){
	        	System.out.println("Exception x");
	        	e.printStackTrace();
	        }

	        return serviceRequest;
		
	}

	public void getStatus(String serviceRequest){
		try{
			HttpURLConnection connection=  WebserviceHelper.getConnection("http://erp.esworkplace.sap.com/sap/bc/srt/xip/sap/ECC_SRVCREQIDQR?sap-client=800", getMessageStatus(serviceRequest));
            
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            	SAXParserFactory factory = SAXParserFactory.newInstance();
                SAXParser saxParser = factory.newSAXParser();
                
                saxParser.parse(connection.getInputStream(), this);
            } 
		}catch(Exception e){}
	}
	
	
	String name ="";
    public void startElement(String uri, String localName,
        String qName, Attributes attributes)
        throws SAXException {
        this.name = this.name+"."+qName;
       
    }

    public void characters(char ch[], int start, int length)
        throws SAXException {
    	String value = new String(ch, start, length);
        if(name.equals(createIgnore + "ServiceRequest.ID")){
        	serviceRequest = value;
        }else if (name.startsWith(queryIgnore)){
        	String key= name.replaceAll(queryIgnore, "");
        	System.out.println(key);
        	statusResult.put(key, value);
        }
     
    }
    
    public void endElement(String uri, String localName,
    		String qName) throws SAXException {
    	  this.name =  this.name.substring(0,   this.name.lastIndexOf(qName)-1);
    	 
    		 
    }

	
    
	public Hashtable<String, String> getStatusResult() {
		return statusResult;
	}
	/**
	 * 
	 * @return String message - the original xml message
	 */
	private String getMessageCreateMessage(String materialID, String description){
		return "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
		+"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">  <SOAP-ENV:Body>    <yq1:ServiceRequestERPCreateRequest_sync xmlns:yq1=\"http://sap.com/xi/EA-APPL/SE/Global\">"
			+"<ServiceRequest>   <IndividualMaterialID>"+materialID+"</IndividualMaterialID>"
			+"<TypeCode>S1</TypeCode><Description>"+description+"</Description>"
			+"</ServiceRequest> </yq1:ServiceRequestERPCreateRequest_sync>"
			+"</SOAP-ENV:Body> </SOAP-ENV:Envelope>";

	}

	private String getMessageStatus(String serviceRequest){
    return 		"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
		+"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
		+"<SOAP-ENV:Body>"
		+"  <yq1:ServiceRequestERPByIDQuery_sync xmlns:yq1=\"http://sap.com/xi/EA-APPL/SE/Global\">"
		+"    <ServiceRequestSelectionByID>"
		+"      <ServiceRequestID>"+serviceRequest+"</ServiceRequestID>"
		+"    </ServiceRequestSelectionByID>"
		+"  </yq1:ServiceRequestERPByIDQuery_sync>"
		+"  </SOAP-ENV:Body>"
		+"	</SOAP-ENV:Envelope>";

	}
}
